<?php

namespace App\Http\Controllers\admin\setting;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

use App\Models\Setting;
use Intervention\Image\ImageManagerStatic as Image;

class SettingController extends Controller
{
    public function index()
    {
        return view('admin.setting.setting');
    }

    public function store(Request $request)
    {
        $data = $request->except('_token','file');
        foreach ($data as $v){
            if(empty($v)){
                return back()->with('success','验证失败请重新填写,请按提示正确填写');
            }
        }

        $setting = new Setting();

        $data['logo'] = $this->file($request);
        if(empty($data['logo'])){
            return back()->with('success','图片没上传');
        }

        $insert = $setting->create($data);
        $bool = $insert->save();
        if($bool){
            return back()->with('success','添加成功');
        }else{
            return back()->with('success','添加失败');
        }
    }

    public function update($id,Request $request)
    {
        $data = $request->except('_token','file','_method');

        $setting =Setting::find($id);

        $data['logo'] = empty($this->file($request))?$setting->logo:$this->file($request);

        $bool = $setting->where('id',$id)->update($data);
        if($bool){
            return back()->with('success','修改成功');
        }else{
            return back()->with('success','修改失败');
        }
    }

    public function edit($id)
    {
       $data = Setting::find($id);


       if(!empty($data)){
           return $data;
       }else{
           return 0;
       }
    }

    public function file(Request $request)
    {
        //dd($request->hasFile('files'));
        if ($request->hasFile('file')) {
            if ($request->file('file')->isValid()) {
                $file = $request->file('file');
                $ext = $file->getClientOriginalExtension();
                $picname = time() . rand(1000, 9999) . '.' . $ext;
                $img = Image::make($file);
                $img->resize(120, null, function ($constraint) {
                    $constraint->aspectRatio();
                    $constraint->upsize();
                });
                $img->save('./upload/'.$picname);

                return $picname;

            }
            return null;
        }
    }
}
